package com.ErpCoreWeb.Workflow;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CBaseObjectMgr;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Workflow.CActives;
import com.ErpCoreModel.Workflow.CActivesDefMgr;
import com.ErpCoreModel.Workflow.CWorkflow;
import com.ErpCoreModel.Workflow.CWorkflowDef;
import com.ErpCoreModel.Workflow.CWorkflowMgr;
import com.ErpCoreModel.Workflow.enumApprovalResult;
import com.ErpCoreModel.Workflow.enumApprovalState;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class ApprovalActives
 */
@WebServlet("/ApprovalActives")
public class ApprovalActives extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CWorkflow m_Workflow = null;
    public CActives m_Actives = null;
    public CBaseObjectMgr m_BaseObjectMgr = null;
    public CBaseObject m_BaseObject = null;
    public UUID m_guidParentId = Util.GetEmptyUUID();
    public CUser m_User = null;
    CCompany m_Company = null; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ApprovalActives() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        
		try {
			String B_Company_id = request.getParameter("B_Company_id");
			if (Global.IsNullParameter(B_Company_id))
				m_Company = Global.GetCtx(this.getServletContext())
						.getCompanyMgr().FindTopCompany();
			else
				m_Company = (CCompany) Global.GetCtx(this.getServletContext())
						.getCompanyMgr().Find(Util.GetUUID(B_Company_id));


			String TbCode = request.getParameter("TbCode");
			String id = request.getParameter("id");
			String WF_Workflow_id = request.getParameter("WF_Workflow_id");
			
			if (Global.IsNullParameter(TbCode)
			    || Global.IsNullParameter(id)
			    || Global.IsNullParameter(WF_Workflow_id))
			{
			    response.getWriter().print("数据不完整！");
			    response.getWriter().close();
			    return;
			}
			
			UUID m_guidParentId= Util.GetEmptyUUID();
			String ParentId = request.getParameter("ParentId");
			if (!Global.IsNullParameter(ParentId))
			    m_guidParentId = Util.GetUUID(ParentId);
			
			CBaseObjectMgr m_BaseObjectMgr = Global.GetCtx(this.getServletContext()).FindBaseObjectMgrCache(TbCode, m_guidParentId);
			if (m_BaseObjectMgr == null)
			{
			    m_BaseObjectMgr = new CBaseObjectMgr();
			    m_BaseObjectMgr.TbCode = TbCode;
			    m_BaseObjectMgr.Ctx = Global.GetCtx(this.getServletContext());
			}
			
			CBaseObject m_BaseObject = m_BaseObjectMgr.Find(Util.GetUUID(id));
			
			CWorkflow m_Workflow = (CWorkflow)m_BaseObjectMgr.getWorkflowMgr().Find(Util.GetUUID(WF_Workflow_id));
			if (m_Workflow.getState() != enumApprovalState.Running)
			{
				response.getWriter().print("只有进行中的工作流才能审批！");
				 response.getWriter().close();
			    return;
			}
			CActives m_Actives = m_Workflow.getActivesMgr().FindNotApproval();
			if (m_Actives == null)
			{
				response.getWriter().print("没有审批的活动！");
				 response.getWriter().close();
			    return;
			}
			
			if (m_Actives.getAType().equals("按用户"))
			{
			    if (!m_Actives.getB_User_id().equals(m_User.getId()))
			    {
			    	response.getWriter().print("没有权限审批！");
			    	response.getWriter().close();
			        return;
			    }
			}
			else //按角色
			{
			    CRole Role =(CRole) m_Company.getRoleMgr().Find(m_Actives.getB_Role_id());
			    if (Role == null || Role.getUserInRoleMgr().FindByUserid(m_User.getId())==null)
			    {
			    	response.getWriter().print("没有权限审批！");
			    	response.getWriter().close();
			        return;
			    }
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("Accept"))
        {
        	Accept();
            return ;
        }
        else if (Action.equalsIgnoreCase("Reject"))
        {
        	Reject();
            return ;
        }
	}

    void Accept()
    {
        m_Actives.setResult ( enumApprovalResult.Accept);
        m_Actives.setComment ( request.getParameter("Comment"));
        m_Actives.setB_User_id ( m_User.getId());

        StringBuffer sErr = new StringBuffer();
        CWorkflowMgr WorkflowMgr = (CWorkflowMgr)m_Workflow.m_ObjectMgr;
        if (!WorkflowMgr.Approval(m_Workflow, m_Actives,  sErr))
        {
        	try {
				response.getWriter().print(sErr.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
    }
    void Reject()
    {
        m_Actives.setResult ( enumApprovalResult.Reject);
        m_Actives.setComment (request.getParameter("Comment"));
        m_Actives.setB_User_id ( m_User.getId());

        StringBuffer sErr = new StringBuffer();
        CWorkflowMgr WorkflowMgr = (CWorkflowMgr)m_Workflow.m_ObjectMgr;
        if (!WorkflowMgr.Approval(m_Workflow, m_Actives,  sErr))
        {
        	try {
				response.getWriter().print(sErr.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
    }
}
